package com.springblog.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.db.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springblog.common.utils.ConvertUtil;
import com.springblog.common.utils.PageUtils;
import com.springblog.entity.BlogEntity;
import com.springblog.entity.JpaEntity;
import com.springblog.entity.vo.BlogVo;
import com.springblog.mapper.BlogMapper;
import com.springblog.mapper.JpaMapper;
import com.springblog.service.JpaService;
import com.springblog.service.BlogService;
import com.springblog.common.utils.R;
import com.springblog.common.utils.ShiroUtils;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.apache.ibatis.ognl.DynamicSubscript.all;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ifredom@gmail.com
 * @since 2022-04-23
 */
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @Autowired
    private JpaService jpaService;

    @Autowired
    private JpaMapper jpaMapper;

    @Autowired
    private BlogMapper blogMapper;

    @GetMapping("/list")
    public R list(@RequestBody Map<String, Object> params) {
        // 使用自定义分页注解切面

        Page page = new Page(1, 5);
        QueryWrapper<BlogEntity> queryWrapper = new QueryWrapper<BlogEntity>().orderByDesc("created");
        PageUtils data = blogService.queryPage(params);

//          System.out.println(limit);
//        System.out.println(currentPage);
//        Page<Blog> page = new Page<>(currentPage, limit);
//        IPage<Blog> list = blogService.page(page, new QueryWrapper<Blog>().orderByAsc("created"));
        return R.ok().put("data", data);
    }
    @GetMapping("/list1")
    public R list1(@RequestBody Map<String, Object> params) {
        QueryWrapper<BlogEntity> queryWrapper = new QueryWrapper<>();
        List<BlogEntity> list = blogMapper.selectList(queryWrapper);

        List<BlogVo> blogVos = ConvertUtil.entityToVoList(list, BlogVo.class);
//        ArrayList<BlogVo> voList = new ArrayList<>();
//        list.forEach(item->{
//            BlogVo voItem = new BlogVo();
//            BeanUtil.copyProperties(item,voItem);
//            voList.add(voItem);
//        });

        return R.ok().put("data", blogVos);
    }

    @GetMapping("/list2")
    public R list2(@RequestBody Map<String, Object> params) {

        List<JpaEntity> all = jpaMapper.findAll();

        return R.ok().put("data", all);
    }

    @GetMapping("/list/{id}")
    public R one(@PathVariable(name = "id") Long id) {
        BlogEntity blogEntity = blogService.getById(id);
        Assert.notNull(blogEntity, "该博客已被删除");
        return R.ok().put("data", blogEntity);
    }

    @PostMapping("/edit")
    public R edit(@Validated @RequestBody BlogEntity blogEntity) {
        BlogEntity temp = null;
        if (blogEntity.getId() != null) {
            temp = blogService.getById(blogEntity.getId());
            Assert.isTrue(temp.getUserId() == ShiroUtils.getUserId());
        } else {
            temp = new BlogEntity();
            temp.setUserId(ShiroUtils.getUserId());
            temp.setStatus(1);
        }
        BeanUtil.copyProperties(blogEntity, temp, "userId", "status", "roleId");
        blogService.saveOrUpdate(temp);

        return R.ok();
    }

    @GetMapping("/one/{id}")
    public R oneDefine(@PathVariable(name = "id") Long id) {
        BlogEntity blogEntity = blogService.queryBlogById(id);
        BlogVo blogVo = ConvertUtil.entityToVo(blogEntity, BlogVo.class);

//        BlogVo blogVo = new BlogVo();
//        BeanUtil.copyProperties(blogEntity, blogVo);


        blogVo.setOtherProperty("前端展示额外字段");

        return R.ok().put("data", blogVo);
    }

    @GetMapping("/two/{id}")
    public R twoDefine(@PathVariable(name = "id") Long id) {
        BlogVo blog = blogService.queryBlogVoById(id);

        return R.ok().put("data", blog);
    }

    // 测试 jaskson序列化，返回值为 null 时进行处理
    @GetMapping("/third")
    public R thirdDefine() {

        BlogEntity blogEntity = new BlogEntity();
        blogEntity.setTitle("新博客");
        blogEntity.setDescription("文章描述");

        String jsonString = "{ \"title\" : \"json博客标题\", \"description\" : \"json文章描述\",\"abc\":6 }";

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(
                DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);


        try {
            BlogEntity blog = objectMapper.readValue(jsonString, BlogEntity.class);

            System.out.println("car brand = " + blog);
            System.out.println("car brand = " + blog.getTitle());
            System.out.println("car doors = " + blog.getDescription());

            String str = objectMapper.writeValueAsString(blogEntity);
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return R.ok();
    }
}
